<?php
declare (strict_types=1);

namespace app\api\middleware;

use app\api\controller\Token;
use think\facade\Db;

//跨域中间件
class Auth
{
    public function handle($request, \Closure $next)
    {
        $headers = getallheaders();
        if (!isset($headers['Api-Token'])) {
            return json(message("请登录", false, [], 401));
        }
        if (empty($headers['Api-Token'])) {
            return json(message("请登录", false, [], 401));
        }
        $JwtObj = new \Jwt();
        $token = $headers['Api-Token'];
        $uid = $JwtObj->verifyToken($token);
        if ($uid == false) {
            return json(message("用户不存在", false, [], 401));
        }
        $user = Db::name('member')
            ->where('id', $uid)
            ->where('mark', 1)
            ->field('token_time_out,id,status')
            ->find();
        if ($user['status'] == 2) {
//                //token过期 刷新token 返回新token值
            return json(message("账号已禁用,请联系管理员", false, [], 401));
        }
        if (time() - $user['token_time_out'] > 10) {
//                //token过期 刷新token 返回新token值
            return json(message("登录超时请重新登录", false, [], 401));
        }
        $request->user_id = isset($user['id']) ? $user['id'] : '';
        return $next($request);
    }

}
